package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.FlavorMapper;
import com.sky.mapper.SetMealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {
    private final DishMapper dishMapper;
    private final FlavorMapper flavorMapper;
    private final SetMealDishMapper setMealDishMapper;

    public DishServiceImpl(DishMapper dishMapper, FlavorMapper flavorMapper, SetMealDishMapper setMealDishMapper) {
        this.dishMapper = dishMapper;
        this.flavorMapper = flavorMapper;
        this.setMealDishMapper = setMealDishMapper;
    }

    //新增菜品
    @Override
    @Transactional
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = Dish.builder()
                .categoryId(dishDTO.getCategoryId())
                .description(dishDTO.getDescription())
                .name(dishDTO.getName())
                .price(dishDTO.getPrice())
                .image(dishDTO.getImage())
                .status(dishDTO.getStatus())
                .build();
        // 保存菜品信息
        dishMapper.insert(dish);
        if (dishDTO.getFlavors() != null && !dishDTO.getFlavors().isEmpty()) {
            //有口味数据，需要保存口味数据
            //设置菜品id
            for (DishFlavor flavor : dishDTO.getFlavors()) {
                flavor.setDishId(dish.getId());
            }
            flavorMapper.insert(dishDTO.getFlavors());
        }
    }

    //条件分页查询菜品
    @Override
    public PageResult queryPageOnConditional(DishPageQueryDTO dishPageQueryDTO) {
        //设置分页
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        //查询菜品
        Page<DishVO> page = dishMapper.queryPageOnConditional(dishPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    //根据id查询菜品及口味
    @Override
    public DishVO getByIdWithFlavor(Long id) {
        return dishMapper.getByIdWithFlavor(id);
    }

    //修改菜品
    @Override
    @Transactional()
    public void update(DishDTO dishDTO) {
        Dish dish = Dish.builder()
                .id(dishDTO.getId())
                .categoryId(dishDTO.getCategoryId())
                .description(dishDTO.getDescription())
                .name(dishDTO.getName())
                .price(dishDTO.getPrice())
                .image(dishDTO.getImage())
                .status(dishDTO.getStatus())
                .build();
        //先删除对应菜品的口味数据
        flavorMapper.deleteByDishId(dish.getId());
        //修改菜品数据
        dishMapper.update(dish);
        //添加新的口味数据
        if (dishDTO.getFlavors() != null && !dishDTO.getFlavors().isEmpty()) {
            //设置菜品id
            dishDTO.getFlavors().forEach(flavor -> flavor.setDishId(dish.getId()));
            flavorMapper.insert(dishDTO.getFlavors());
        }
    }

    //批量删除菜品
    @Override
    public void deleteById(List<Long> ids) {
        //这里的思路是,删除传递的id中可以删除的(停售以及无关联套餐的菜品,对于无法删除的在给予前端消息提示,待完善)
        /*//定义一个集合,存储需要删除的菜品id
        List<Long> removeDishIds = new ArrayList<>();
        //根据ids查询所有的菜品
        List<Dish> dishList = dishMapper.getBatchByIds(ids);
        for (Dish dish : dishList) {
            //判断菜品是否禁售
            if (dish.getStatus() != 1) {
                int rows = setMealDishMapper.getCount(dish.getId());
                //判断菜品是否关联了套餐,无关联,添加到可删除集合中
                if (rows == 0) {
                    removeDishIds.add(dish.getId());
                }
            }
        }
        //批量删除菜品
        if (!removeDishIds.isEmpty()) {
            dishMapper.deleteById(removeDishIds);
        }
        //如果删除的菜品数量和提交菜品总数量不一致,抛出业务异常,提示菜品关联了套餐或正在售卖
        if (dishList.size() > removeDishIds.size()) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL + "/" + MessageConstant.DISH_ON_SALE);
        }*/

        List<Dish> dishList = dishMapper.getBatchByIds(ids);
        //判断菜品是否禁售
        for (Dish dish : dishList) {
            //判断菜品是否禁售
            if (dish.getStatus() != 0) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        //判断菜品是否关联了套餐
        int rows = setMealDishMapper.getCount(ids);
        if (rows != 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //批量删除菜品
        dishMapper.deleteBatchByIds(ids);
        //删除菜品口味数据
        flavorMapper.deleteBatchByDishIds(ids);
    }

    //启用禁用菜品
    @Override
    public void startOrStop(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status).build();
        dishMapper.update(dish);
    }

    //根据分类id查询菜品
    @Override
    public List<Dish> list(Long categoryId) {
        return dishMapper.getDishByCategoryId(categoryId);
    }
}
